package cn.hpclub.server.controller.admin;

import java.sql.SQLException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

import cn.hpclub.server.bean.OrgNode;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.tx.Tx;

import cn.hpclub.server.model.Banner;
import cn.hpclub.server.service.BannerService;
import cn.hpclub.server.util.InterfaceUtil;

public class BannerController extends BaseAdminController<Banner>{

    /**
     * @Title: list
     * @Description: 列表
     */
    public void list(){
        ConcurrentHashMap<String, String> searchInfo = getSearchInfo();;
        findByPageForSearch("select *, (select org.DisplayName from organization org where org.id = b.org_id) as org_name ",
                            new BannerService().service.getSqlExceptSelect(searchInfo));
        setAttrs(searchInfo);

        render("/admin/banner.tpl");
    }

    /**
     * @Title: delete
     * @Description: 删除
     */
    @Before(Tx.class)
    public void delete() throws SQLException{
        String[] ids = getParaValues("ids");
        if(ids == null || ids.length <= 0){
            ajaxJsonErrorMessage("删除失败，无选中项");
        }

        boolean deleted = deleteBannerByIDs(ids);

        if(deleted){
            ajaxJsonSuccessMessage("删除成功！");
        } else{
            ajaxJsonErrorMessage("删除失败！");
            throw new SQLException("广告删除失败");
        }
    }

    /**
     * @Title: add
     * @Description: 新增
     */
    public void add(){
        setAttr("bannerID", -1);
        initCityLevelOrgList();
        render("/admin/banner_add.tpl");
    }

    /**
     * @Title: save
     * @Description: 新增/编辑时的保存 (id为-1时为新增)
     */
    public void save(){
        int id = getParaToInt("bannerID");

        if(-1 == id){
            addBanner();
        } else{
            editBanner();
        }

        redirect("/banner/list");
    }

    private void editBanner(){
        Banner banner = getModel(Banner.class);
        banner.set("id", getPara("bannerID"));
        banner.set("name", getPara("bannerName"));
        banner.set("cover_image", getPara("bannerImageUrl"));
        banner.set("activity_url", getPara("bannerUrl"));
        banner.set("type", getPara("bannerType"));
        banner.set("server_type", getPara("serverType"));
        banner.set("org_id", getPara("orgID"));
        banner.set("sort", getPara("bannerSort"));
        banner.set("enabled", getPara("enabled"));
        banner.set("last_updated_by", InterfaceUtil.getAdminId());
        banner.set("last_updated_time", new Date());

        banner.update();
    }

    private void addBanner(){
        Banner banner = getModel(Banner.class);
        banner.set("name", getPara("bannerName"));
        banner.set("cover_image", getPara("bannerImageUrl"));
        banner.set("activity_url", getPara("bannerUrl"));
        banner.set("type", getPara("bannerType"));
        banner.set("server_type", getPara("serverType"));
        banner.set("sort", getPara("bannerSort"));
        banner.set("org_id", getPara("orgID"));
        banner.set("enabled", getPara("enabled"));
        banner.set("created_by", InterfaceUtil.getAdminId());
        banner.set("created_time", new Date());

        banner.save();
    }

    /**
     * @Title: edit
     * @Description: 编辑
     */
    public void edit(){
        String id = getPara("id");
        initCityLevelOrgList();
        Banner banner = Banner.dao.findById(id);

        setAttr("bannerID", banner.getInt("id"));
        setAttr("bannerName", banner.getStr("name"));
        setAttr("bannerType", banner.getInt("type"));
        setAttr("serverType", banner.getInt("server_type"));
        setAttr("bannerImageUrl", banner.getStr("cover_image"));
        setAttr("bannerUrl", banner.getStr("activity_url"));
        setAttr("bannerSort", banner.getInt("sort"));
        setAttr("enabled", banner.getInt("enabled"));
        setAttr("orgID", banner.getInt("org_id"));

        render("/admin/banner_add.tpl");
    }

    private void initCityLevelOrgList(){
        List<Map.Entry<String, Integer>> list = new ArrayList<>();
        list.add(new AbstractMap.SimpleEntry<String, Integer>("大掌柜", 54470));
        list.addAll(getCityLevelOrgList());
        setAttr("orgs", list);
    }
    /**
     * @Title: getOrgMaps
     * @Description:获取市级分公司构集合
     * @return Map<String,Integer>
     */
    private List<Map.Entry<String, Integer>> getCityLevelOrgList(){
        List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>();

        OrgNode root = InterfaceUtil.getOrgTree(InterfaceUtil.getIdTop(), 1, false);
        if(root == null || root.getSubNode() == null || root.getSubNode().size() == 0){
            return list;
        }
        /* 大掌柜根节点，显示所有地市分公司 */
        int accountOrgId = InterfaceUtil.getOrgId();
        if(accountOrgId == root.getId()){
            for(OrgNode node : root.getSubNode()){
                list.add(new AbstractMap.SimpleEntry<String, Integer>(node.getDisplayName(), node.getId()));
            }
        } else{
            for(OrgNode node : root.getSubNode()){
                if(accountOrgId == node.getId()){
                    list.add(new AbstractMap.SimpleEntry<String, Integer>(node.getDisplayName(), node.getId()));
                }
            }
        }
        return list;
    }
    private boolean deleteBannerByIDs(String[] ids){
        boolean deleted = true;
        for(String id : ids){
            Banner banner = new Banner();
            banner.set("id", id);
            banner.set("is_deleted", 1);
            banner.set("last_updated_by", InterfaceUtil.getAdminId());
            banner.set("last_updated_time", new Date());
            if(!banner.update()){
                deleted = false;
                break;
            }
        }

        return deleted;
    }
}
